package org.rcgwt.client.ui.calendar.model.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.rcgwt.client.ui.calendar.i18n.CalendarUtils;

/**
 * The Calendar event manager (who provided all the information needed to manage
 * events)
 * 
 * @author Elian ORIOU
 * 
 */

@SuppressWarnings("deprecation")
public class CalendarEventManager {

	private List<Event> events;

	public CalendarEventManager() {
		events = new ArrayList<Event>();
	}

	public void addEvent(Event e) {
		events.add(e);
	}

	public List<Event> getEvents() {
		return events;
	}

	public boolean isSelectable(Date d) {
		for (Event e : events) {
			if (e.getStartTime().before(d) && e.getEndTime().after(d)) {
				return false;
			}
		}
		return true;
	}

	public Period getEventPeriodDuringMonth(Event e, int month, int year) {
		Date startTime = e.getStartTime();
		Date endTime = e.getEndTime();

		int startMonth = startTime.getMonth();
		int endMonth = endTime.getMonth();

		int startYear = startTime.getYear() + 1900;
		int endYear = endTime.getYear() + 1900;

		Period p = null;
		Date start = new Date(year - 1900, month, 1);
		Date end = new Date(year - 1900, month, CalendarUtils.getDaysNumber(
				year, month));

		switch (e.getFrequency()) {
		case EVERYDAY:
			return new Period(start, end);
		case EVERYYEAR:
			if (startMonth == month) {
				return new Period(startTime, endTime);
			}
			break;
		case EVERYMONTH:
			return new Period(startTime, endTime);
		}

		/* 1st case */
		if (year == startYear && year == endYear) {
			if (startMonth < month && endMonth == month) {
				p = new Period(start, endTime);
			} else if (startMonth == month && endMonth > month) {
				p = new Period(startTime, end);
			} else if (startMonth == month && endMonth == month) {
				p = new Period(startTime, endTime);
			} else if (startMonth < month && endMonth > month) {
				p = new Period(start, end);
			}
		}
		/* 2nd case */
		else if (year == startYear && year < endYear) {
			if (month > startMonth) {
				p = new Period(start, end);
			} else if (month == startMonth) {
				p = new Period(startTime, end);
			}
		}
		/* 3rd case */
		else if (year > startYear && year < endYear) {
			p = new Period(start, end);
		}
		/* 4rd case */
		else if (year > startYear && year == endYear) {
			if (endMonth == month) {
				p = new Period(start, endTime);
			} else if (month < endMonth) {
				p = new Period(start, end);
			}
		}
		return p;
	}
}
